package com.example.shipload_e.util;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.widget.Toast;

public class HttpUtil {
	private static final int	SO_TIMEOUT	       = 60000;
	private static final int	CONNECTION_TIMEOUT	= 30000;
	private static String	   USER_AGENT	       = "Android";
	private static CookieStore	cookieStore	       = null;

	/**
	 * 以传统模式提交数据
	 * @param url
	 * @param entity
	 * @return
	 */
	public static String doPost(String url,HttpEntity entity,Context ctx) {
		HttpPost request = new HttpPost(url);
		request.setEntity(entity);
		return doPostWithCookie(request, ctx);
	}

	/**
	 * 以ajax的形式提交数据
	 * @param url
	 * @param entity
	 * @return
	 */
	public static String doAjaxPost(String url,HttpEntity entity,Context ctx) {
		HttpPost request = new HttpPost(url);
		request.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
		request.setEntity(entity);
		return doPostWithCookie(request, ctx);
	}

	/**
	 * 附加cookie提交数据
	 * @param request
	 * @return
	 */
	public static String doPostWithCookie(HttpUriRequest request,Context ctx) {
		String result = null;
		HttpParams httpParams = new BasicHttpParams();
		try {
			try {
				HttpProtocolParams.setUserAgent(httpParams, USER_AGENT);
				DefaultHttpClient dhc = new DefaultHttpClient(httpParams);
				dhc.setCookieStore(cookieStore);
				HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTION_TIMEOUT);
				HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
				dhc.setParams(httpParams);
				// dhc.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, SO_TIMEOUT);//
				// 设置请求超时
				// dhc.getParams()
				// .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);//
				// 设置传输超时
				HttpResponse response = null;
				response = dhc.execute(request);
				if(response.getStatusLine().getStatusCode() == 200) {
					cookieStore = dhc.getCookieStore();
					result = EntityUtils.toString(response.getEntity(), "UTF-8");
					/* 获取并保存Cookie值 */
					PersistentCookieStore myCookieStore = new PersistentCookieStore(ctx);
					List<Cookie> cookies = dhc.getCookieStore().getCookies();
					for(Cookie cookie : cookies) {
						myCookieStore.addCookie(cookie);
					}
					myCookieStore.getCookies();
				} else if(response.getStatusLine().getStatusCode() == 404) {
					Toast.makeText(ctx, "网络地址不存在，请联系管理人员处理。。。", Toast.LENGTH_SHORT).show();
				} else if(response.getStatusLine().getStatusCode() == 503) {
					Toast.makeText(ctx, "系统异常，请退出登陆后再重试。。。", Toast.LENGTH_SHORT).show();
				}
				if(request.isAborted()) {
					request.abort();
				}
				return result;
			} catch (SocketTimeoutException e) {
				return HttpConstant.NETWORK_UNAVAILABLE;
			} catch (ConnectTimeoutException e) {

				return HttpConstant.TIME_OUT_EXCEPTION;
			} catch (ClientProtocolException e) {
				e.printStackTrace();
				result = HttpConstant.NETWORK_UNAVAILABLE;
				return result;
			} catch (IOException e) {
				e.printStackTrace();
				result = HttpConstant.NETWORK_UNAVAILABLE;
			}
		} catch (Exception e) {
			e.printStackTrace();
			result = HttpConstant.NETWORK_UNAVAILABLE;
		}
		return result;
	}

	/**
	 * 通过url发送post请求，返回请求结果
	 * @param url
	 * @param params
	 * @return
	 */
	public static StringBuffer queryStringForPost(String url,Map<String, String> params,Context ctx) {
		try {
			List<NameValuePair> msg = new ArrayList<NameValuePair>();
			JSONObject jobj = new JSONObject();
			for(String key : params.keySet()) {
				jobj.put(key, params.get(key));
			}
			msg.add(new BasicNameValuePair(HttpConstant.TAG_PARAM, jobj.toString()));
			HttpEntity entity = new UrlEncodedFormEntity(msg, HTTP.UTF_8);

			return new StringBuffer(doAjaxPost(url, entity, ctx));
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 提交参数里有文件的数据
	 * @param url
	 * @param file
	 * @return
	 * @throws Exception
	 */
	public static StringBuffer uploadPictureUtil(Context ctx,String url,File file) throws Exception {
		MultipartEntity entity = new MultipartEntity();
		// 添加文件参数
		if(file != null && file.exists()) {
			entity.addPart("file", new FileBody(file));
			// 添加经纬度坐标参数
			// GetLocationInfo gps = new GetLocationInfo(ctx);
			// Map<String, String> result = gps.getLocationInfoByNetWork();
			// JSONObject jobj = new JSONObject();
			// jobj.put("latitude", result.get("latitude"));
			// jobj.put("longitude", result.get("longitude"));
			// entity.addPart(HttpConstant.TAG_PARAM, new StringBody(jobj.toString()));
		}
		return new StringBuffer(doPost(url, entity, ctx));
	}

}
